package router

import (
	// "fmt"

	"net/http"
	"strings"
	"yunpan/app"
	"yunpan/db"
	"yunpan/handler"
	"yunpan/pool"

	"github.com/gin-gonic/gin"
)

func HTTPInterceptor() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 修改表单解析逻辑，因为不是所有请求都是 multipart 形式
		if c.ContentType() == "multipart/form-data" {
			if err := c.Request.ParseMultipartForm(10 << 20); err != nil {
				c.JSON(http.StatusBadRequest, gin.H{
					"code": 400,
					"msg":  "解析表单数据失败",
				})
				c.Abort()
				return
			}
		}

		// 从 Header 中获取 token
		token := c.GetHeader("Authorization")
		if token != "" {
			// 去掉 "Bearer " 前缀
			token = strings.TrimPrefix(token, "Bearer ")
			// fmt.Println("Received token:", token)
		}

		// 从 Header 中获取 username
		username, err := db.GetUsername(token)
		if err != nil {
			c.JSON(http.StatusForbidden, gin.H{
				"code": 403,
				"msg":  "登陆过期，请重新登陆",
			})
			c.Abort()
			return
		}
		if !handler.IsTokenValid(token) {
			c.JSON(http.StatusForbidden, gin.H{
				"code": 403,
				"msg":  "无效的令牌",
			})
			c.Abort()
			return
		}

		// 将用户名保存到上下文中，供后续处理函数使用
		// c.Set("username", username)
		c.Set("username", username)
		c.Next()
	}
}

// SetupRoutes 设置路由
func SetupRoutes(r *gin.Engine, dbPool *pool.DBWorkerPool) {
	// 添加CORS中间件
	r.Use(CORSMiddleware())

	// API路由组
	api := r.Group("/api")
	{
		// 用户相关API
		api.POST("/user/signup", handler.SignupHandler)
		api.POST("/user/signin", handler.SigninHandler)
		api.POST("/user/info", HTTPInterceptor(), handler.UserInfoHandler)

		// 文件相关API
		api.POST("/file/upload", HTTPInterceptor(), func(c *gin.Context) {
			ctx := app.GetContext()
			handler.UploadHandler(c, ctx.HashPool, ctx.DBPool, ctx.CephPool)
		})
		api.GET("/file/meta", HTTPInterceptor(), handler.FileQueryHandler)
		//api.GET("/file/download", HTTPInterceptor(), handler.DownloadHandler)
		//api.DELETE("/file/delete", HTTPInterceptor(), handler.DeleteFile)
		api.PUT("/file/update", HTTPInterceptor(), handler.FileMetaUpdateHandler)

		// 分块上传相关API
		api.POST("/file/mpupload/init", HTTPInterceptor(), handler.InitialMuItipartUploadHandler)
		api.POST("/file/mpupload/uppart", HTTPInterceptor(), handler.UploadPartHandler)
		api.POST("/file/mpupload/complete", HTTPInterceptor(), handler.CompleteUploadHandler)

		// 流处理路由
		api.POST("/stream/upload", HTTPInterceptor(), func(c *gin.Context) {
			ctx := app.GetContext()
			handler.StreamUploadHandler(c, ctx.CephPool)
		})

		api.GET("/stream/play", HTTPInterceptor(), handler.StreamPlayHandler)

	}

	// 添加文件相关路由
	fileGroup := r.Group("/api/file")
	{
		fileGroup.GET("/list", HTTPInterceptor(), handler.GetFileList)
		fileGroup.POST("/rename", HTTPInterceptor(), handler.RenameFile)
		fileGroup.POST("/createFolder", HTTPInterceptor(), handler.CreateFolder)
		fileGroup.DELETE("/delete/:id", HTTPInterceptor(), handler.DeleteFile)
		fileGroup.POST("/share", HTTPInterceptor(), handler.CreateShare)
		fileGroup.GET("/preview/:id", HTTPInterceptor(), handler.PreviewFile)
		fileGroup.GET("/download/:id", HTTPInterceptor(), handler.DownloadHandler)

		fileGroup.GET("/trash", HTTPInterceptor(), func(c *gin.Context){
			handler.GetTrashList(c, dbPool)
		})
		fileGroup.POST("/restore", HTTPInterceptor(), handler.RestoreFile)
		fileGroup.POST("/permanent-delete", HTTPInterceptor(), handler.PermanentlyDeleteFile)

	}
}

// CORSMiddleware CORS中间件
func CORSMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin,Authorization,Content-Type,Username")
		c.Writer.Header().Set("Access-Control-Max-Age", "86400") // 缓存预检请求结果 24 小时

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
